package com.kexuexiong.demo.bear.common.exception;

import com.kexuexiong.demo.bear.common.dto.Result;
import com.netflix.client.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionHandler {

    @org.springframework.web.bind.annotation.ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionException(MethodArgumentNotValidException e){
        List<String> validation = e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        return Result.fail(validation,Result.E1000,"入参错误");
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(ClientException.class)
    public Result handleClientException(ClientException e){
        return Result.fail(e.getMessage(),Result.E1000,"系统维护中");
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.fail("",Result.E1001,"服务器异常！");
    }
}
